/**
 * WebDurak Active Game Page utilities
 */
var cardRanks = {
		"SIX" : 6,
		"SEVEN" : 7,
		"EIGHT" : 8,
		"NINE" : 9,
		"TEN" : 10,
		"JACK" : 11,
		"QUEEN" :12,
		"KING" : 13,
		"ACE" : 14
}

setInterval(refreshState, 1000);

var commandVersion = -1;
var kozarSuit;
var possibleCardsToAttack = new Array();
var attackCardsSoFar = new Array();
var defendCards = new Array();

function MoreLegalCardstoAttack() {

	var isAble = false;

	if ($(".attackCardDiv").children("img").length == 0 && attackCardsSoFar.length == 0) {
		$.each($("#hand").children(), function (key, data) {
			possibleCardsToAttack.push(data);
		});
		isAble = true;
		return isAble;
	} else {
		possibleCardsToAttack = [];
		var cardsOnTheTable = new Array();
		$.each($(".attackCardDiv"), function (key, data) {
			if(data.children.length != 0) {
				cardsOnTheTable.push(data);
			}
		});
		$.each($(".defendCardDiv"), function (key, data) {
			if(data.children.length != 0) {
				cardsOnTheTable.push(data);
			}
		});
		cardsOnTheTable = cardsOnTheTable.concat(attackCardsSoFar);
		var handCards = $(".handCardDiv").toArray();
		$.each(cardsOnTheTable, function(key, cardOnTable) {
			$.each(handCards, function(key, handCard) {
				if ($(handCard).attr("rank") == $(cardOnTable).attr("rank")) {
					if(possibleCardsToAttack.indexOf(handCard) == -1) {
						isAble = true;
						possibleCardsToAttack.push(handCard);
					}
				}
			});
		});
	}
	return isAble;
}

function isLegalDefend(defendCard, attackCardIndex) {
	var ret = false;
	var attackCard = $("#attackCardDiv" + attackCardIndex).get(0);
	if(attackCard != null) {
		if(($(defendCard).attr("suit") == $(attackCard).attr("suit")) &&
				(cardRanks[$(defendCard).attr("rank")] > cardRanks[$(attackCard).attr("rank")])) {
			ret = true;
		} else if(($(defendCard).attr("suit") == kozarSuit) &&
				($(attackCard).attr("suit") != kozarSuit)) {
			ret = true;
		}
	}
	return ret;
}

function iter(obj, indent) {
	for ( var key in obj) {
		if (typeof (obj[key]) == 'object') {
			iter(obj[key], indent + "\t");
		} else {
			console.log(indent + "Key: " + key + " Values: " + obj[key]);
		}
	}
}
function showWaitingMessage(data) {

}

function getImageFileName(rank, suit) {
	return rank + "_" + suit + ".png";
}

function refreshTableState(data) {
	/*
	 * Show the Hand
	 */
	var hand_div = $("#hand");
	hand_div.hide();
	hand_div.empty();
	$.each(data.cards.cards, function(key, value) {
		console.log("Rank is: " + value.rank + " Suit is " + value.suit);
		hand_div.append("<div class='handCardDiv' id='handCard" + key
				+ "' rank='" + value.rank +"' suit='"+ value.suit + "'><img class='handCard' src='images/"
				+ getImageFileName(value.rank, value.suit) + "'/></div>");
		$("#handCard" + key).addClass("image_regular");
		$("#handCard" + key).draggable({
			revert: "invalid"
		});
		$("#handCard" + key).hover(
				function () {
					$(this).addClass("image_highlight");
					$(this).removeClass("image_regular");
				},
				function () {
					$(this).addClass("image_regular");
					$(this).removeClass("image_highlight");
				}
		);
	});
	hand_div.show();

	/*
	 * Show the Cards on the Table
	 */
	var attack_cards = $("#attack_cards");
	attack_cards.hide();
	$(".attackCardDiv").empty();
	$.each(data.gameState.cardsOnTheTable.attackCards, function(key, value) {
		var currentCard = $("#attackCardDiv" + key); 
		currentCard.append("<img class='tableCard' src='images/"
				+ getImageFileName(value.rank, value.suit) + "'/>");
		currentCard.hover(
				function () {
					$(this).addClass("image_highlight");
					$(this).removeClass("image_regular");
				},
				function () {
					$(this).addClass("image_regular");
					$(this).removeClass("image_highlight");
				}
		);
		currentCard.attr("rank", value.rank);
		currentCard.attr("suit", value.suit);
	});
	if(data.command == "S2C_ATTACK"){
		$("#messages").html("You are the attacker, please drag the card you choose to the marked places on the table");
		$(".attackCardDiv").droppable({
			hoverClass: "ui-state-active",
			drop: function( event, ui ) {
				MoreLegalCardstoAttack();
				if(possibleCardsToAttack.indexOf($(ui.draggable).get(0)) != -1 && attackCardsSoFar.indexOf($(ui.draggable).get(0)) == -1)
					attackCardsSoFar.push($(ui.draggable).get(0));
				else
					$(ui.draggable).draggable( "option", "revert", true );
				MoreLegalCardstoAttack();
			},
			accept: ".handCardDiv",
			tolerance: "touch"
		});
		$(".attackCardDiv").droppable("enable");
	} else {
		$(".attackCardDiv").droppable();
		$(".attackCardDiv").droppable("disable");
	}
	attack_cards.show();

	var defend_cards = $("#defend_cards");
	defend_cards.hide();
	$(".defendCardDiv").empty();
	$.each(data.gameState.cardsOnTheTable.defendCards, function(key, value) {
		if(value.rank && value.suit) {
			var currentCard = $("#defendCardDiv" + key);
			currentCard.append("<img class='tableCard' src='images/"
					+ getImageFileName(value.rank, value.suit) + "'/>");
			currentCard.hover(
					function () {
						$(this).addClass("image_highlight");
						$(this).removeClass("image_regular");
					},
					function () {
						$(this).addClass("image_regular");
						$(this).removeClass("image_highlight");
					}
			);
			currentCard.attr("rank", value.rank);
			currentCard.attr("suit", value.suit);
		}
	});
	defend_cards.show();
	if(data.command == "S2C_DEFEND"){
		$("#message").text("You were attacked, please defend");
		$(".defendCardDiv").droppable({
			hoverClass: "ui-state-active",
			drop: function( event, ui ) {
				var i = this.id.match(/defendCardDiv(\d)/)[1];
				if(isLegalDefend($(ui.draggable).get(0), i) == true) {
					defendCards[i] = $(ui.draggable).get(0);
				} else {
					$(ui.draggable).draggable( "option", "revert", true );
				}
			},
			accept: ".handCardDiv",
			tolerance: "touch"
		});
		$(".defendCardDiv").droppable("enable");
	} else {
		$(".defendCardDiv").droppable();
		$(".defendCardDiv").droppable("disable");
	}
	/*
	 * Show Cozar
	 */
	defend_cards.position({
        of:  attack_cards,
        my: "left top",
        at: "left center",
        collision: "none",
        offset: "30 0"
    });
	$("#kozar_card").hide();
	$("#kozar_card").empty();
	$("#kozar_card").append("<img class='cardSize' src='images/" + 
			getImageFileName(data.gameState.kozar.rank,	data.gameState.kozar.suit) + "'/>");
	$("#kozar_card").show();
	kozarSuit = data.gameState.kozar.suit;
}

function refreshState() {
	$("#message").text("refreshed...");
	$.getJSON("runningGame", {"command" : "C2S_GET_GAME_STATE"}, function(data) {
	console.log("Got response" + data);
	handle_response(data);
	});
}

function handle_response(data) {
	if (data != null) {
		if (data.redirect) {
			console.log("Got redirect" + data.redirect);
			// data.redirect contains the string URL to redirect to
			window.location.href = data.redirect;
		}
		if(commandVersion != data.version) {
			commandVersion = data.version;

			if (data.gameState.gameStarted == false) {
				showWaitingMessage(data);
			} else {
				refreshTableState(data);
			}
			iter(data, "");
		}
	}
}
$(function() {
    $( "#attackButton" )
        .button()
        .click(function( event ) {
        	var attackCards = new Array();
        	$.each(attackCardsSoFar, function(key, data) {
        		var card = {};
        		card.rank =  $(data).attr("rank");
        		card.suit =  $(data).attr("suit");
        		attackCards.push(card);
        	});
        	var mydata = {
        			"command" : "C2S_ATTACKED",
        			"numOfCards" : attackCards.length,
        			"cards" : attackCards
        		};
        	$.getJSON("runningGame", mydata, function(data) {
        		console.log("Got response " + data);
        		handle_response(data);
        	});
        	attackCardsSoFar = [];
        });
});

$(function() {
    $( "#defendButton" )
        .button()
        .click(function( event ) {
        	var cardsToSend = new Array();
        	$.each(defendCards, function(key, data) {
        		if($(data).attr("rank") != undefined && $(data).attr("suit") != undefined) {
        			var card = {};
        			card.rank =  $(data).attr("rank");
        			card.suit =  $(data).attr("suit");
        			cardsToSend.push(card);
        		}
        	});
        	var mydata = {
        			"command" : "C2S_DEFENDED",
        			"numOfCards" : cardsToSend.length,
        			"cards" : cardsToSend
        		};
        	$.getJSON("runningGame", mydata, function(data) {
        		console.log("Got response " + data);
        		handle_response(data);
        	});
        	defendCards = [];
        });
});

$(function() {
    $( "#withdrawButton" )
        .button()
        .click(function( event ) {
        	var mydata = {
        			"command" : "C2S_WITHDRAWN"
        	};
        	$.getJSON("runningGame", mydata, function(data) {
        		console.log("Got response " + data);
        		handle_response(data);
        	});
        	defendCards = [];
        });
});

$(function() {
    $( "#passAttackButton" )
        .button()
        .click(function( event ) {
        	var mydata = {
        			"command" : "C2S_PASS_ATTACK"
        	};
        	$.getJSON("runningGame", mydata, function(data) {
        		console.log("Got response " + data);
        		handle_response(data);
        	});
        	defendCards = [];
        });
});